package com.jack.lib.net.loading

import androidx.lifecycle.coroutineScope
import com.jack.lib.core.ext.lifeRecycle
import com.jack.lib.core.net.JNetView
import com.jack.lib.core.net.NetLoadingMode
import kotlinx.coroutines.*

/**
 * author : chong.huang
* create : 2/14/21
 * desc   :
 */
class CommonLoading(private val loadingMode: NetLoadingMode, private val view: JNetView) : Loading() {

    private lateinit var loadingJob: Job

    override fun create() {
        loadingJob = view.lifecycle().coroutineScope.launch(Dispatchers.Main) {
            val delayMs = when (loadingMode) {
                NetLoadingMode.SHOW -> 0L
                NetLoadingMode.DELAY -> 500L
                NetLoadingMode.HIDE -> -1L
            }
            if (delayMs != -1L){
                delay(delayMs)
                view.showLoading()
            }
        }
    }

    override fun cancel() {
        loadingJob.cancel()
        view.lifecycle().coroutineScope.launch(Dispatchers.Main) { view.hideLoading() }
    }
}